package com.tyut.musicdreamer.framework.starter.web.advice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tyut.musicdreamer.framework.starter.convention.exception.AbstractException;
import com.tyut.musicdreamer.framework.starter.convention.result.Result;
import com.tyut.musicdreamer.framework.starter.web.Results;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一返回结构（已停用）
 * 仅当类或方法显式标记了@WrapResult注解时才会包装响应
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.tyut.musicdreamer"})
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 默认不包装响应，仅当显式标记了@WrapResult注解时才会包装
        // 注意：此处可能需要修改您的服务配置，使其不默认包装响应
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                ServerHttpRequest request, ServerHttpResponse response) {
        log.debug("ResponseBodyAdvice处理返回值: {}", body);
        
        // 如果已经是 Result 类型，直接返回
        if (body instanceof Result) {
            return body;
        }
        
        // 如果是异常，包装为错误响应
        if (body instanceof AbstractException) {
            AbstractException ex = (AbstractException) body;
            return Results.failure(ex.getErrorCode(), ex.getErrorMessage());
        }
        
        // 处理 String 类型的特殊情况
        if (body instanceof String) {
            // 设置正确的内容类型
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            // 必须返回字符串，否则会出现类型转换异常
            return JSON.toJSONString(Results.success(body), 
                SerializerFeature.PrettyFormat, 
                SerializerFeature.WriteMapNullValue);
        }
        
        // 其他类型，包装为成功响应
        return Results.success(body);
    }
} 